package mobileann.mafamily.utils;

import java.lang.reflect.Method;
import java.util.List;

import com.mofind.android.base.L;

import mobileann.mafamily.act.main.FS;
import android.content.ContentResolver;
import android.content.Context;
import android.content.ContextWrapper;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.provider.Settings;
import android.telephony.TelephonyManager;

/**
 * 主要功能 : 网络连接状态的工具类
 * <br>NetUtils(Context)
 * <br>netstate()
 * <br>isWifiConnected()
 * <br>getNetType()
 * <br>getNetTypeDetails()
 * <br>hasWifi()
 * <br>isMobileConnected()
 * <br>hasMobileConnected()
 * <br>setWifi(boolean)
 * <br>isWifiEnabled()
 * <br>setWifiStatus(boolean)
 * <br>mobileConnected()
 * <br>acquireWifiLock()
 * <br>releaseWifiLock()
 * <br>createWifiLock()
 * <br>IsCanUseSdCard()
 * <br>isCanUseSim()
 * <br>setMobileNetEnable()
 * <br>invokeMethod(String, Object[])
 * <br>invokeBooleanArgMethod(String, boolean)
 * <br>WifiNeverDormancy(Context)
 * @annotation ADRIAN
 *
 */
public class NetUtils extends ContextWrapper {
	private WifiManager mWm = null;

	private NetUtils(Context base) {
		super(base);
		if (mWm == null) {
			mWm = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
		}
	}

	private static NetUtils g_Instance = null;

	public static synchronized NetUtils getInstance() {
		if (g_Instance == null) {
			g_Instance = new NetUtils(FS.getInstance());
		}
		//
		return g_Instance;
	}

	/**
	 *  判断当前的网络状态 &ADRIAN.2015.8.11.12.20
	 *<br>0 ---- 离线状态
	 *<br>1 ---- 移动网络
	 *<br>2 ---- 只是wifi连接
	 */
	public int netstate() {
		int i = 0;
		if (isMobileConnected() && !isWifiConnected()) {
			i = 1;
		} else if (isWifiConnected()) {
			i = 2;
		} else if (!isMobileConnected() && !isWifiConnected()) {
			i = 0;
		}
		return i;
	}

	/** 是否是wifi连接状态 @ADRIAN.2015.8.11.12.23 */
	private boolean isWifiConnected() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		State wifi = State.DISCONNECTED;
		if (ni != null) {
			wifi = ni.getState();
		}
		return (wifi == State.CONNECTED);
	}

	/** 
	 * 获取此时连接网络的状态 &ADRIAN.2015.8.11.12.25 
	 * <br>unknow
	 * <br>2G
	 * <br>3G
	 * <br>4G
	 * <br>mobile
	 */
	public String getNetType(){
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = cm.getActiveNetworkInfo();
		String type = "unknown";
		if(info != null){
			if(info.getType() == ConnectivityManager.TYPE_WIFI){
				type = "WIFI";
			}
			if(info.getType() == ConnectivityManager.TYPE_MOBILE){
				switch(info.getSubtype()){
				case TelephonyManager.NETWORK_TYPE_GPRS:
				case TelephonyManager.NETWORK_TYPE_EDGE:
				case TelephonyManager.NETWORK_TYPE_CDMA:
				case TelephonyManager.NETWORK_TYPE_1xRTT:
				case TelephonyManager.NETWORK_TYPE_IDEN:
					type = "2G";
					break;
				case TelephonyManager.NETWORK_TYPE_UMTS:
				case TelephonyManager.NETWORK_TYPE_EVDO_0:
				case TelephonyManager.NETWORK_TYPE_EVDO_A:
				case TelephonyManager.NETWORK_TYPE_EVDO_B:
				case TelephonyManager.NETWORK_TYPE_HSDPA:
				case TelephonyManager.NETWORK_TYPE_HSPA:
				case TelephonyManager.NETWORK_TYPE_HSPAP:
				case TelephonyManager.NETWORK_TYPE_HSUPA:
				case TelephonyManager.NETWORK_TYPE_EHRPD:
					type = "3G";
					break;
				case TelephonyManager.NETWORK_TYPE_LTE:
					type = "4G";
					break;
				case TelephonyManager.NETWORK_TYPE_UNKNOWN:
				default:
					type = "mobile";
					break;
				}
			}
//						Log.i("net-type", "网络类型："+type);
			//			Toast.makeText(this, "网络类型："+type, Toast.LENGTH_SHORT).show();
		}
		return type;
	}
	
	/**
	 * 主要功能:获取网络的详细信息,具体的网络类型
	 * @return
	 */
	public String getNetTypeDetails(){
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = cm.getActiveNetworkInfo();
		String type = "UNKNOWN";
		if(info != null){
			if(info.getType() == ConnectivityManager.TYPE_WIFI){
				type = "WIFI";
			}
			if(info.getType() == ConnectivityManager.TYPE_MOBILE){
				switch(info.getSubtype()){
				case TelephonyManager.NETWORK_TYPE_GPRS:
					type = "GPRS";
					break;
				case TelephonyManager.NETWORK_TYPE_EDGE:
					type = "EDGE";
					break;
				case TelephonyManager.NETWORK_TYPE_CDMA:
					type = "CDMA";
					break;
				case TelephonyManager.NETWORK_TYPE_1xRTT:
					type = "1xRTT";
					break;
				case TelephonyManager.NETWORK_TYPE_IDEN:
					type = "IDEN";
					break;
				case TelephonyManager.NETWORK_TYPE_UMTS:
					type = "UMTS";
					break;
				case TelephonyManager.NETWORK_TYPE_EVDO_0:
					type = "EVDO_0";
					break;
				case TelephonyManager.NETWORK_TYPE_EVDO_A:
					type = "EVDO_A";
					break;
				case TelephonyManager.NETWORK_TYPE_EVDO_B:
					type = "EVDO_B";
					break;
				case TelephonyManager.NETWORK_TYPE_HSDPA:
					type = "HSDPA";
					break;
				case TelephonyManager.NETWORK_TYPE_HSPA:
					type = "HSPA";
					break;
				case TelephonyManager.NETWORK_TYPE_HSPAP:
					type = "HSPAP";
					break;
				case TelephonyManager.NETWORK_TYPE_HSUPA:
					type = "HSUPA";
					break;
				case TelephonyManager.NETWORK_TYPE_EHRPD:
					type = "EHRPD";
					break;
				case TelephonyManager.NETWORK_TYPE_LTE:
					type = "LTE";
					break;
				case TelephonyManager.NETWORK_TYPE_UNKNOWN:
					type = "UNKNOWN";
					break;
				default:
					type = "MOBILE";
					break;
				}
			}
		}
		return type;
	}
	
	/**
	 * 主要功能:
	 * <br> 获取扫描的wifi的结果
	 * @return 是否有wifi的扫描结果
	 */
	public boolean hasWifi(){
		if(!isWifiEnabled()){
			return true;
		}
		List<ScanResult> results = mWm.getScanResults();
		if(results == null)
			return false;
		int size = results.size();
		if(size > 0){
			return true;
		}else{
			return false;
		}
	}

	/**
	 * 主要功能:
	 * <br> 判断移动网络连接的状态
	 * @return
	 */
	private boolean isMobileConnected() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		State wifi = State.DISCONNECTED;
		if (ni != null) {
			wifi = ni.getState();
		}
		return (wifi == State.CONNECTED);
	}
	
	/**
	 * 主要功能:
	 * <br> 是否有移动网络连接
	 * @return
	 * @annotation ADRIAN.2015.8.11.14.46
	 */
	public boolean hasMobileConnected(){
		return isMobileConnected();
	}

	/**
	 * 是否设置wifi
	 * @param isEnable
	 * @annotation ADRIAN.2015.8.11.14.48
	 */
	public void setWifi(boolean isEnable) {
		if (isEnable == true) {
			if (!mWm.isWifiEnabled()) {
				mWm.setWifiEnabled(true);                
			}
		} else {
			if (mWm.isWifiEnabled()) {
				mWm.setWifiEnabled(false);                
			}
		}
	}

	/**
	 * 主要功能:
	 * <br> 判断wifi是否可用
	 * @return
	 * @annotation ADIRAN.2015.8.11.14.48
	 */
	public boolean isWifiEnabled() {        
		return mWm.isWifiEnabled();
	}

	/**
	 * 设置wifi的状态
	 * @param isEnable
	 * @annotation ADIRAN.2015.8.11.14.49
	 */
	public void setWifiStatus(boolean isEnable){
		mWm.setWifiEnabled(isEnable);
	}

	/**
	 * 是否是移动网络连接的状态
	 * @return
	 * @annotation ADRIAN.2015.8.11.14.50
	 */
	public boolean mobileConnected(){
		return isMobileConnected();
	}

	public void acquireWifiLock() {
	}

	public void releaseWifiLock() {
	}

	public void createWifiLock() {
	}

	/**
	 * 判断SD卡是否能够使用
	 * @return
	 */
	public boolean IsCanUseSdCard() {
		try {
			return Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED);
		} catch (Exception e) {
			L.e("maf", "error--", e);
		}
		return false;
	}

	/**
	 * SIM卡是否能够使用
	 * @return
	 * @annotation ADRIAN.2015.8.11.14.51
	 */
	public boolean isCanUseSim() {
		try {
			TelephonyManager mgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
			return TelephonyManager.SIM_STATE_READY == mgr.getSimState();
		} catch (Exception e) {
			L.e("maf", "error--", e);
		}
		return false;
	}

	/**
	 * 开启系统设置里的移动网络
	 */
	public final void setMobileNetEnable() {
		ConnectivityManager mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		Object[] arg = null;
		try {
			boolean isMobileDataEnable = invokeMethod("getMobileDataEnabled",
					arg);
			if (!isMobileDataEnable) {
				invokeBooleanArgMethod("setMobileDataEnabled", true);
			}
		} catch (Exception e) {
			L.e("maf", "error--", e);
		}
	}

	/**
	 * 利用反射的方法,打开wifi
	 * @param methodName
	 * @param arg
	 * @return
	 * @throws Exception
	 */
	public boolean invokeMethod(String methodName, Object[] arg)
			throws Exception {
		ConnectivityManager mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		Class ownerClass = mConnectivityManager.getClass();
		Class[] argsClass = null;
		if (arg != null) {
			argsClass = new Class[1];
			argsClass[0] = arg.getClass();
		}
		Method method = ownerClass.getMethod(methodName, argsClass);
		Boolean isOpen = (Boolean) method.invoke(mConnectivityManager, arg);
		return isOpen;
	}

	/**
	 * 通过反射的方法,将此变量设置为值
	 * @param methodName
	 * @param value
	 * @return
	 * @throws Exception
	 */
	public Object invokeBooleanArgMethod(String methodName, boolean value)
			throws Exception {
		ConnectivityManager mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		Class ownerClass = mConnectivityManager.getClass();
		Class[] argsClass = new Class[1];
		argsClass[0] = boolean.class;
		Method method = ownerClass.getMethod(methodName, argsClass);
		return method.invoke(mConnectivityManager, value);
	}

	/**
	 * WIFI状态下永不休眠
	 * @param mContext
	 */
	public void WifiNeverDormancy(Context mContext) {
		ContentResolver resolver = mContext.getContentResolver();
		int value = Settings.System.getInt(resolver,
				Settings.System.WIFI_SLEEP_POLICY,
				Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
		if (Settings.System.WIFI_SLEEP_POLICY_NEVER != value) {
			Settings.System.putInt(resolver, Settings.System.WIFI_SLEEP_POLICY,
					Settings.System.WIFI_SLEEP_POLICY_NEVER);
		}
		System.out.println("wifi value:" + value);
	}
	/*
	 * 上面这个函数，会自动修改我们WIFI设置中的高级选项，将其设置为一直保持连接。不用使用其他控件就可以解决。
	 * 
	 * 需要注意的是此函数在调用时必须现在AndroidManifest.xml中声明权限
	 * 
	 * <uses-permission android:name="android.permission.WRITE_SETTINGS"/>
	 */
}
